//
// Created by ziya on 2021/10/18.
//

#include "hpp/ManageThread.h"
#include "hpp/TaskPool.h"
#include "hpp/ThreadPool.h"

extern TaskPool taskPool;
extern ThreadPool threadPool;

pthread_cond_t  ManageThread::_cond;

pthread_mutex_t ManageThread::_lock;

bool ManageThread::is_lock = false;

void* ManageThreadPool(void *arg) {

    while (true){

        int task_count = taskPool.task_count();

        int live_size = threadPool._live_size;

        int busy_size  = threadPool._busy_size;

        int max_size   = threadPool._max_size;

        int core_size = threadPool._core_size;

        if(0 == task_count && 0 == busy_size){
            pthread_mutex_lock(&ManageThread::_lock);

            ManageThread::is_lock = true;

            pthread_cond_wait(&ManageThread::_cond,&ManageThread::_lock);

            pthread_mutex_unlock(&ManageThread::_lock);
        }

        if(0 != task_count && live_size == busy_size && live_size < max_size){
            INFO_PRINT(" 需要扩容  task_count=%d  live_size=%d  busy_size=%d  max_size=%d",task_count , live_size  , busy_size, max_size);

            threadPool.expand();

        }


        if ((0 == task_count) && (0 == busy_size) && (live_size > core_size)) {
            INFO_PRINT("[管理线程]需要缩减: live size=%d, busy size=%d, max size=%d\n", live_size, busy_size, max_size);

            threadPool.shrink();
        }

        sleep(1);
    }
}

void ManageThread::init(){
    is_lock = false;
    pthread_mutex_init(&_lock,NULL);
    pthread_cond_init(&_cond,NULL);
}
void ManageThread::run(){
    pthread_t tid;
    pthread_create(&tid,NULL,ManageThreadPool,NULL);


}
